<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { ref, reactive } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import { phoneRules } from "../utils/rule";
import type { FormInstance } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { useVerifyCode } from "../utils/verifyCode";
import { useUserStoreHook } from "@/store/modules/user";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Iphone from "@iconify-icons/ep/iphone";

const { t } = useI18n();
const loading = ref(false);
const ruleForm = reactive({
  phone: "",
  verifyCode: ""
});
const ruleFormRef = ref<FormInstance>();
const { isDisabled, text } = useVerifyCode();

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 模拟登录请求，需根据实际开发进行修改
      setTimeout(() => {
        message(transformI18n($t("login.sgmwauthlogin" + "成功！")), {
          type: "success"
        });
        loading.value = false;
      }, 2000);
    } else {
      loading.value = false;
      return fields;
    }
  });
};

function onBack() {
  useVerifyCode().end();
  useUserStoreHook().SET_CURRENTPAGE(0);
}

function gotoSGMW() {
  console.log(window.location.origin);
  const prefixUrl = `${import.meta.env.VITE_APP_OidcUrl}auth`;
  const clientId = import.meta.env.VITE_APP_OidcId;
  let redirectUrl = import.meta.env.VITE_APP_OidcRedirect;
  if (!redirectUrl.startsWith("http")) {
    redirectUrl = `${window.location.origin}${redirectUrl}`;
  }

  // VITE_APP_OidcRedirect='/oidc/auth'

  const url = `${prefixUrl}?response_type=code&scope=openid&redirect_uri=${redirectUrl}&state=&client_id=${clientId}`;

  console.log(url);
  // alert(url);
  //https://account-test.sgmw.com.cn/auth/realms/demo/protocol/openid-connect/auth?response_type=code&scope=openid&redirect_uri=http://localhost:8848/oidc/auth&state=&client_id=bjptpmc-front
  window.location.href = url;
}
</script>

<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="phoneRules" size="large">
    <Motion :delay="150">
      <el-form-item>
        <el-button
          class="w-full"
          size="large"
          type="primary"
          :loading="loading"
          color="purple"
          @click="gotoSGMW"
        >
          {{ t("login.sgmwauthlogin") }}
        </el-button>
      </el-form-item>
    </Motion>

    <Motion :delay="200">
      <el-form-item>
        <el-button class="w-full" size="default" @click="onBack">
          {{ t("login.back") }}
        </el-button>
      </el-form-item>
    </Motion>
  </el-form>
</template>
